<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<link href="css/templatemo_style.css" rel="stylesheet">
<link href="css/templatemo_misc.css" rel="stylesheet">
<script
	src="https://maps.googleapis.com/maps/api/js?v=3.exp?sensor=false"></script>
<script type="text/javascript">
	var origins = new Array();
	var tableDist1 = new Array();
	var tableDist = new Array();
	var map, dms;
	var dirService, dirRenderer;
	var highlightedCell;
	var routeQuery;
	var bounds;
	var panning = false;

	window.onload = 	$.ajax({
		url : "addLocal",
		type : 'GET',
		dataType : 'json',
		contentType : 'application/json',
		mimeType : 'application/json',

		success : function(data) {

			$.each(data, function(index, value) {
				value2 = value.toString();
				origins[origins.length] = value2;
			});
			console.log(origins);
			initialize();
		}
	});

	function initialize() {

	

		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				var latitude = position.coords.latitude;
				var longitude = position.coords.longitude;
				console.log(latitude + " " + longitude);

				var coords = new google.maps.LatLng(latitude, longitude);
				geocoder = new google.maps.Geocoder();

				geocoder.geocode({
					'latLng' : coords
				}, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						if (results[0]) {
							coords_addr = results[0].formatted_address;
							console.log(coords_addr);

							destinations = [ coords_addr, ];

							query = {
								origins : origins,
								destinations : destinations,
								travelMode : google.maps.TravelMode.WALKING,
								unitSystem : google.maps.UnitSystem.IMPERIAL
							};

							var mapOptions = {
								zoom : 12,
								center : new google.maps.LatLng(coords),
								mapTypeId : google.maps.MapTypeId.ROADMAP
							}
							map = new google.maps.Map(document
									.getElementById("map"), mapOptions);
							createTable();

							for (var i = 0; i < origins.length; i++) {
								origins[i];
							}

							for (var j = 0; j < destinations.length; j++) {
								destinations[j];
							}

							dms = new google.maps.DistanceMatrixService();

							dirService = new google.maps.DirectionsService();
							dirRenderer = new google.maps.DirectionsRenderer({
								preserveViewport : true
							});
							dirRenderer.setMap(map);

							google.maps.event.addListener(map, 'idle',
									function() {
										if (panning) {
											map.fitBounds(bounds);
											panning = false;
										}
									});

							updateMatrix();
						}
					}
				});
			});
		}
		else {
			var div = document.getElementById("gallery-content");
		div.innerHTML="Twoja przegladarka nie wspiera geolokacji"+ "<br />" + "Wykrycie aktualnego polozenia nie bylo mozliwe";
		}
	}

	function updateMatrix() {
		dms.getDistanceMatrix(query, function(response, status) {
			if (status == "OK") {
				populateTable(response.rows);
				addDistance(response.rows);
				
				for (i=0; i< tableDist.length; i++){
					if (tableDist[i].indexOf(" stóp")> -1) {
						var a = tableDist[i].split(" ");
						console.log(a[0]);
						tableDist1.push(parseFloat(a[0])/5280);
						}else
								{
					var a = tableDist[i].split(" ");
					console.log(a[0]);
					tableDist1.push(parseFloat(a[0]));
					}
				}
				console.log(tableDist1);
				
				console.log(indexOfSmallest(tableDist1));
				var near = document.getElementById("nearest");
				near.innerHTML="Zapraszamy do najblizszego lokalu"+ "<br />" + origins[indexOfSmallest(tableDist1)];
				
				}
		});
	}

	function createTable() {
		var table = document.getElementById('matrix');
		var tr = addRow(table);
		addElement(tr);
		for (var j = 0; j < destinations.length; j++) {
			var td = addElement(tr);
			td.setAttribute("class", "destination");
			td.appendChild(document.createTextNode(destinations[j]));
		}

		for (var i = 0; i < origins.length; i++) {
			var tr = addRow(table);
			var td = addElement(tr);
			td.setAttribute("class", "origin");
			td.appendChild(document.createTextNode(origins[i]));
			for (var j = 0; j < destinations.length; j++) {
				var td = addElement(tr, 'element-' + i + '-' + j);
				td.onmouseover = getRouteFunction(i, j);
				td.onclick = getRouteFunction(i, j);
			}
		}
	}

	function populateTable(rows) {
		for (var i = 0; i < rows.length; i++) {
			for (var j = 0; j < rows[i].elements.length; j++) {
				var distance = rows[i].elements[j].distance.text;
				var duration = rows[i].elements[j].duration.text;
				var td = document.getElementById('element-' + i + '-' + j);
				td.innerHTML = distance + "<br/>" + duration;
			}
		}
	}

	function addDistance(rows) {
		for (var i = 0; i < rows.length; i++) {
			for (var j = 0; j < rows[i].elements.length; j++) {
				var td = document.getElementById('element-' + i + '-' + j);
				tableDist.push(rows[i].elements[j].distance.text);
			}
		}
	}

	function getRouteFunction(i, j) {
		return function() {
			routeQuery = {
				origin : destinations[j],
				destination : origins[i],
				travelMode : query.travelMode,
				unitSystem : query.unitSystem,
			};

			if (highlightedCell) {
				highlightedCell.style.backgroundColor = "#ffffff";
			}
			highlightedCell = document.getElementById('element-' + i + '-' + j);
			highlightedCell.style.backgroundColor = "#e0ffff";
			showRoute();
		}
	}

	function showRoute() {
		dirService.route(routeQuery, function(result, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				dirRenderer.setDirections(result);
				bounds = new google.maps.LatLngBounds();
				bounds.extend(result.routes[0].overview_path[0]);
				var k = result.routes[0].overview_path.length;
				bounds.extend(result.routes[0].overview_path[k - 1]);
				panning = true;
				map.panTo(bounds.getCenter());
			}
		});
	}

	function updateMode() {
		switch (document.getElementById("mode").value) {
		case "driving":
			query.travelMode = google.maps.TravelMode.DRIVING;
			break;
		case "walking":
			query.travelMode = google.maps.TravelMode.WALKING;
			break;
		}
		updateMatrix();
		if (routeQuery) {
			routeQuery.travelMode = query.travelMode;
			showRoute();
		}
	}

	function updateUnits() {
		switch (document.getElementById("units").value) {
		case "km":
			query.unitSystem = google.maps.UnitSystem.METRIC;
			break;
		case "mi":
			query.unitSystem = google.maps.UnitSystem.IMPERIAL;
			break;
		}
		updateMatrix();
	}

	function addRow(table) {
		var tr = document.createElement('tr');
		table.appendChild(tr);
		return tr;
	}

	function addElement(tr, id) {
		var td = document.createElement('td');
		if (id) {
			td.setAttribute('id', id);
		}
		tr.appendChild(td);
		return td;
	}

	Array.min = function( array ){
	    return Math.min.apply( Math, array );
	};

	function indexOfSmallest(a) {
		 var value = Math.min.apply(null, a);
		 console.log(value);
		 return a.indexOf(value);
		}
</script>
<style>
#container {
	left: 355px;
}

.content {
	top: 400px;
	left: 80px;
}

#map {
	width: 300px;
	height: 196px;
	border: 1px solid grey;
}

#matrix {
	font-size: 10px;
	color: black;
	border-collapse: collapse;
	margin-top: -240px;
	margin-left: 350px;
	width: 300px;
}

#nearest {
font-style: oblique;
font-size: 20px;
color: #65a8dd;
text-align: center;
margin-top: 20px;
width:700px;
}

#description {
color: #a2c044;
text-align: center;
margin-top: 10px;
width:700px;
font-style: oblique;
font-size: 14px;

}

#controls {
	left: -250px;
	top: 400px;
	text-align: center;
	width: 400px;
}

.origin, .destination {
	font-weight: bold;
	text-align: center;
	background-color: #65a8dd;
	color: white;
}

td {
	border: 1px solid grey;
	width: 80px;
	cursor: default;
	background-color: #ffffff;
}
</style>



<div id="gallery-content">
	<!-- <header> <H2><b>WITAJ!!!</b> </H2></header> -->

	<div class="content gallery">
		<div id="map"></div>
		<div id="controls">
			<select id="mode" onChange="updateMode()">
				<option value="driving">Jade samochodem</option>
				<option value="walking" selected="selected">Ide pieszo</option>
			</select><br /> <select id="units" onChange="updateUnits()">
				<option value="km">Mierzone w kilometrach</option>
				<option value="mi" selected="selected">Mierzone w milach</option>
			</select>
		</div>
		<table id="matrix"></table>
		<div id="nearest"></div>
		<div id="description">
		Aby poznac trase z twojej lokalizacji do danego lokalu <br />nakieruj myszka na obliczona odleglosc miedzy punktami.
		</div>
	</div>
</div>